﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HandyControl.Controls;
using ExclApplication = Microsoft.Office.Interop.Excel.Application;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Reflection;
using clf.weighing.entity;

namespace weighing
{
    /// <summary>
    /// CustomizeEXCLPrintBillWin.xaml 的交互逻辑
    /// </summary>
    public partial class CustomizeEXCLPrintBillWin : GlowWindow
    {

        private ObservableCollection<FileItem> fileItems = new();
        private bool isSetDefaultValue = false;

        private ExclApplication excelApp = null;
        private Worksheet worksheet = null;
        private Workbook workbook = null;

        public CustomizeEXCLPrintBillWin()
        {
            InitializeComponent();

            this.fileLv.ItemsSource = fileItems;
        }

        #region window event
        private void GlowWindow_Loaded(object sender, RoutedEventArgs e)
        {

            if (App.Config.WeighingConfig.WeighingMode == WeighingMode.Simple)
            {
                this.MixPanl.Visibility = Visibility.Visible;
                this.TypePanel.Visibility = Visibility.Collapsed;
            }
            else
            {
                this.TypePanel.Visibility = Visibility.Visible;
                this.MixPanl.Visibility = Visibility.Collapsed;
            }

            ShowSpecialDirection();

            LoadData();
        }

        private void GlowWindow_ContentRendered(object sender, EventArgs e)
        {
            SetDefaultItemSource();

            SelectConfigValue();
        }

        private void GlowWindow_Unloaded(object sender, RoutedEventArgs e)
        {

        }

        private void GlowWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                // 清理资源 窗口和系统退出时洗理
                if (worksheet != null) Marshal.ReleaseComObject(worksheet);
                if (workbook != null)
                {
                    workbook.Close(false);
                    Marshal.ReleaseComObject(workbook);
                }
                if (excelApp != null)
                {
                    excelApp.Quit();
                    Marshal.ReleaseComObject(excelApp);
                }
                // 强制垃圾收集
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("洗理:" + ex.Message);
            }
        }
        #endregion
        private void ShowSpecialDirection()
        {
            string path = " 指定目录: "+ Constant.EXCLBillPath;
            this.InstallTB.Text = path;
        }

        #region open preview
        private void OpenEXclBtn_Click(object sender, RoutedEventArgs e)
        {
            var btn = sender as System.Windows.Controls.Button;
            FileItem? fileItem = btn?.Tag as FileItem;
            if (fileItem != null)
            {
                if (!File.Exists(fileItem.FilePath))
                {
                    Debug.WriteLine("发生错误:" + " 文件模板不存在");
                    return;
                }
                // 创建 Excel 应用程序实例
                 excelApp = new ExclApplication();
                 worksheet = null;
                 workbook = null;
                try
                {
                    // 创建一个新的工作簿
                    workbook = excelApp.Workbooks.Open(fileItem.FilePath);
                    worksheet = (Worksheet)workbook.Sheets[1];

                    //打开 Excl 
                    excelApp.Visible = true;
                    //worksheet.PrintPreview();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("发生错误:" + ex.Message);
                }
            }
            else
            {
                Growl.Info("请选择文件模板");
            }
        }

        private void PreviewBtn_Click(object sender, RoutedEventArgs e)
        {
            var btn = sender as System.Windows.Controls.Button;
            FileItem? fileItem = btn?.Tag as FileItem;
            if (fileItem != null)
            {
                if (!File.Exists(fileItem.FilePath))
                {
                    Debug.WriteLine("发生错误:" + " 文件模板不存在");
                    return;
                }
                // 创建 Excel 应用程序实例
                 excelApp = new ExclApplication();
                 worksheet = null;
                 workbook = null;
                try
                {
                    // 创建一个新的工作簿
                    workbook = excelApp.Workbooks.Open(fileItem.FilePath);
                    worksheet = (Worksheet)workbook.Sheets[1];

                    //替换打印内容
                    setMockBillToExcl(worksheet);

                    //打开 Excl 
                   excelApp.Visible = true;
                    worksheet.PrintPreview();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("发生错误:" + ex.Message);
                }
           
            }
            else
            {
                Growl.Info("请选择文件模板");
            }
        }

        private void setMockBillToExcl(Worksheet worksheet)
        {

            var nameDic = CommonFunction.GetBillTitleFieldNameDic();
            if(nameDic.Count() <= 0)
            {
                Growl.Clear();
                Growl.Error("无法获取磅单变量与数据字段的对映关系");
                return;
            }

            var mBill = getMockBill();

            // 获取总行数
            int totalRows = worksheet.UsedRange.Rows.Count;
            // 获取总列数
            int totalColumns = worksheet.UsedRange.Columns.Count;
            #region 替换打印内容
            Debug.WriteLine("开始替换打印内容");
            mBill.printDateTime = DateTime.Now;
            for (int i = 1; i <= totalRows; i++)
            {
                for (int j = 1; j <= totalColumns; j++)
                {
                    var value = "";
                    Microsoft.Office.Interop.Excel.Range? dataRanger = worksheet.Cells[i, j] as Microsoft.Office.Interop.Excel.Range;
                    if (dataRanger == null) continue;

                    string str = dataRanger.Text?.ToString() ?? "";
                    if (string.IsNullOrEmpty(str))
                    {
                        str = dataRanger.Value?.ToString() ?? "";
                    }
                    if (string.IsNullOrEmpty(str))
                    {
                        str = dataRanger.Value2?.ToString() ?? "";
                    }
                    Debug.WriteLine("value:" + dataRanger.Value?.ToString() ?? "");
                    Debug.WriteLine("value2" + dataRanger.Value2?.ToString() ?? "");

                    if (str.StartsWith("[") && str.EndsWith("]"))
                    {
                        var title = str.Replace("[", "").Replace("]", "");
                        string fieldName = nameDic.Keys.Contains(title) ? nameDic[title] : "";
                        if (string.IsNullOrEmpty(fieldName))
                        {
                            continue;
                        }
                        value = "";
                        FieldInfo? fi = mBill.GetType().GetField(fieldName);
                        if (fi != null)
                        {
                            if (fi.GetValue(mBill) is DateTime dt)
                            {
                                value = dt.ToString("yyyy-MM-dd hh:mm:ss") ?? "";
                            }
                            else
                            {
                                value = fi.GetValue(mBill)?.ToString() ?? "";
                            }
                        }
                        worksheet.Cells[i, j] = value.Replace("/", "-");
                    }
                }
            }

            Debug.WriteLine("结束替换打印内容");
            #endregion
        }

        private WeighingBill getMockBill() {
            return new WeighingBill()
            {
                id = 1876880646671,
                type = App.Config.WeighingConfig.WeighingMode == WeighingMode.Simple ? (int)WeightingBillType.Mixture:(int)WeightingBillType.Buy,
                number = "XS-BD-20250108040003",
                sendCompanyName = "云南测试有限公司",
                receiveCompanyName = "测试客户A有限公司",
                materialName = "费一是",
                inTime = DateTime.Now,
                outTime = DateTime.Now,
                grossWeight =new decimal( 50.170),
                traeWeight = new decimal(10.170),
                netWeight = new decimal(39.200) ,
                carNumber = "鲁NF9999",
                driver = "刘志",
                driverMobile = "13969200001",
                addUserName = "陈龙飞",
                remark = "测试EXCL"
            };
        }


        //设置变量
        private void SetVriablesBtn_Click(object sender, RoutedEventArgs e)
        {

            var btn = sender as System.Windows.Controls.Button;
            FileItem? fileItem = btn?.Tag as FileItem;
            var nameDic = CommonFunction.GetBillTitleFieldNameDic();
            if (nameDic.Count() <= 0)
            {
                Growl.Clear();
                Growl.Error("无法获取磅单变量与数据字段的对映关系");
                return;
            }
            if (fileItem != null)
            {
                if (!File.Exists(fileItem.FilePath))
                {
                    Debug.WriteLine("设置变量发生错误:" + " 文件模板不存在");
                    return;
                }
                // 创建 Excel 应用程序实例
                excelApp = new ExclApplication();
                worksheet = null;
                workbook = null;
                try
                {
                    // 创建一个新的工作簿
                    workbook = excelApp.Workbooks.Open(fileItem.FilePath);
                    if (workbook.Worksheets.Count <= 1)
                    {
                        // 添加一个新工作表，并命名为 "磅单变量"
                        worksheet = (Worksheet)workbook.Sheets.Add();
                        worksheet.Name = "磅单变量";
                    }
                    else
                    {
                        worksheet = (Worksheet)workbook.Sheets[2];
                    }
                    worksheet.Name = "磅单变量";
                    //打开 Excl 
                    excelApp.Visible = false;

                    int start = 2;
                    worksheet.Cells[1, 2] = "磅单变量";
                    var ran = worksheet.get_Range("B1", "B1");
                    ran.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                    ran.RowHeight = 18;
                    ran.ColumnWidth = 50;
                    ran.Font.Size = 18;
                    foreach (var item in nameDic)
                    {
                        worksheet.Cells[start, 2] = "[" + item.Key + "]";
                        start++;
                    }
                    excelApp.DisplayAlerts = false;
                    workbook.SaveAs(fileItem.FilePath);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("设置变量发生错误:" + ex.Message);
                }
                finally
                {            
                    // 清理资源 窗口和系统退出时洗理
                    if (worksheet != null) Marshal.ReleaseComObject(worksheet);
                    if (workbook != null)
                    {
                        workbook.Close(false);
                        Marshal.ReleaseComObject(workbook);
                    }
                    if (excelApp != null)
                    {
                        excelApp.Quit();
                        Marshal.ReleaseComObject(excelApp);
                    }
                    // 强制垃圾收集
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
            else
            {
                Growl.Info("请选择文件模板");
            }       
        }
        #endregion



        private void RefreshBtn_Click(object sender, RoutedEventArgs e)
        {
            LoadData();

            SetDefaultItemSource();

            SelectConfigValue();
        }



        private void SetDefaultItemSource()
        {
           var list = fileItems.ToList();
            list.Add(new FileItem()
            {
                Index = 0,
                Name = "使用默认",
                FilePath = "",
            });
            if (App.Config.WeighingConfig.WeighingMode == WeighingMode.Simple)
            {
                this.MixtureCb.ItemsSource = list;
            }
            else
            {
                this.BuyCb.ItemsSource = list;
                this.SaleCb.ItemsSource = list;
                this.SelfCb.ItemsSource = list;
                this.ForeignCb.ItemsSource = list;
            }

        }

        /// <summary>
        /// 选择已经配制好的值
        /// </summary>
        private void SelectConfigValue()
        {
            isSetDefaultValue = true;
            if (App.Config.WeighingConfig.WeighingMode == WeighingMode.Simple)
            {
                if (fileItems.Count() > 0)
                {
                    for (int i = 0; i < fileItems.Count(); i++)
                    {
                        if (fileItems[i].FilePath.Equals(App.Config.BillPrintConfig.MixtureExclFile))
                        {
                            this.MixtureCb.SelectedIndex = i;
                            break;
                        }
                    }
                }
            }
            else
            {
                if (fileItems.Count() > 0)
                {
                    for (int i = 0; i < fileItems.Count(); i++)
                    {
                        if (fileItems[i].FilePath.Equals(App.Config.BillPrintConfig.BuyExclFile))
                        {
                            this.BuyCb.SelectedIndex = i;
                        }
                        if (fileItems[i].FilePath.Equals(App.Config.BillPrintConfig.SaleExclFile))
                        {
                            this.SaleCb.SelectedIndex = i;
                        }
                        if (fileItems[i].FilePath.Equals(App.Config.BillPrintConfig.ForeginExclFile))
                        {
                            this.ForeignCb.SelectedIndex = i;
                        }
                        if (fileItems[i].FilePath.Equals(App.Config.BillPrintConfig.SelfExclFile))
                        {
                            this.SelfCb.SelectedIndex = i;
                        }
                    }
                }
            }
            this.isUserEXcl_Cb.IsChecked = App.Config.BillPrintConfig.IsUserExclCustomBill;
            isSetDefaultValue = false;
        }

        #region 模板选择
        //采购模板选择
        private void MixtureCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!isSetDefaultValue)
            {
                var item = this.MixtureCb.SelectedItem as FileItem;
                if (item != null && !item.FilePath.Equals(App.Config.BillPrintConfig.MixtureExclFile))
                {
                    App.Config.BillPrintConfig.MixtureExclFile = item.FilePath;
                    CommonFunction.UpdateAppConfig(nameof(BillPrintConfig));
                }
            }
        }

        private void BuyCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!isSetDefaultValue)
            {
                var item = this.BuyCb.SelectedItem as FileItem;
                if (item != null && !item.FilePath.Equals(App.Config.BillPrintConfig.BuyExclFile))
                {
                    App.Config.BillPrintConfig.BuyExclFile = item.FilePath;
                    CommonFunction.UpdateAppConfig(nameof(BillPrintConfig));
                }
            }
        }

        private void SaleCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!isSetDefaultValue)
            {
                var item = this.SaleCb.SelectedItem as FileItem;
                if (item != null && !item.FilePath.Equals(App.Config.BillPrintConfig.SaleExclFile))
                {
                    App.Config.BillPrintConfig.SaleExclFile = item.FilePath;
                    CommonFunction.UpdateAppConfig(nameof(BillPrintConfig));
                }
            }

        }

        private void SelfCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!isSetDefaultValue)
            {
                var item = this.SelfCb.SelectedItem as FileItem;
                if (item != null && !item.FilePath.Equals(App.Config.BillPrintConfig.SelfExclFile))
                {
                    App.Config.BillPrintConfig.SelfExclFile = item.FilePath;
                    CommonFunction.UpdateAppConfig(nameof(BillPrintConfig));
                }
            }
        }

        private void ForeignCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!isSetDefaultValue)
            {
                var item = this.ForeignCb.SelectedItem as FileItem;
                if (item != null && !item.FilePath.Equals(App.Config.BillPrintConfig.ForeginExclFile))
                {
                    App.Config.BillPrintConfig.ForeginExclFile = item.FilePath;
                    CommonFunction.UpdateAppConfig(nameof(BillPrintConfig));
                }
            }
        }
        #endregion


        private void LoadData()
        {
            fileItems.Clear();
            var items = GetExcelFiles();

            if (items != null)
            {
                foreach (var item in items)
                {
                    fileItems.Add(item);
                }
            }
            else
            {
                var path = System.IO.Path.Combine(Environment.CurrentDirectory, "bill");
                Growl.Error($"请先去定义后 将 .xlxs 文件 放在{path}，刷新就会有了");
            }
        }

        /// <summary>
        /// 获取指定目录下的所有 .xlsx 文件的全路径
        /// </summary>
        /// <param name="directoryPath">要搜索的目录路径</param>
        /// <returns>包含 .xlsx 文件全路径的列表</returns>
        public List<FileItem> GetExcelFiles(string directoryPath = "")
        {
            List<FileItem> excelFiles = new();
            if (string.IsNullOrEmpty(directoryPath))
            {
                directoryPath = System.IO.Path.Combine(Environment.CurrentDirectory, "bill");
            }
            if (Directory.Exists(directoryPath) == false)
            {
                Directory.CreateDirectory(directoryPath);

                return excelFiles;
            }

            try
            {
                // 获取目录下的所有文件信息
                var files = Directory.GetFiles(directoryPath, "*.xlsx", SearchOption.AllDirectories);

                for (int i = 0; i < files.Length; i++)
                {
                    var file = files[i];
                    if(file.StartsWith("~$") || file.Contains("~$") || file.Contains("~") || file.Contains("$"))
                    {
                        continue;
                    }
                    excelFiles.Add(new FileItem()
                    {
                        Index = i,
                        FilePath = file,
                        Name = System.IO.Path.GetFileName(file)
                    });
                }
            }
            catch (Exception ex)
            {
                Growl.Error($"异常: {ex.Message}");
            }

            return excelFiles;
        }



        private void Cb_Checked(object sender, RoutedEventArgs e)
        {
            if (isSetDefaultValue) return;
            App.Config.BillPrintConfig.IsUserExclCustomBill = true;
            int res = CommonFunction.UpdateAppConfig(nameof(BillPrintConfig));
            Debug.WriteLine("IsUserExclCustomBill :" + res);
        }
        private void Cb_Unchecked(object sender, RoutedEventArgs e)
        {
            if (isSetDefaultValue) return;
            App.Config.BillPrintConfig.IsUserExclCustomBill = false;
            int res = CommonFunction.UpdateAppConfig(nameof(BillPrintConfig));
            Debug.WriteLine("IsUserExclCustomBill :" + res);
        }

    }

    public class FileItem
    {
        public int Index { get; set; } = 0;
        public string Name { get; set; } = "";
        public string FilePath { get; set; } = "";
    }
}